import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/commonApi.dart';
import 'package:ct_pa_majordomo/utils/date_tools.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

class BusinessLicensePage extends StatefulWidget {
  final OnlinePayState state;
  final VoidCallback onStateChanged;
  final bool isReadOnly;

  const BusinessLicensePage({
    super.key,
    required this.state,
    required this.onStateChanged,
    this.isReadOnly = false,
  });

  @override
  State<BusinessLicensePage> createState() => _BusinessLicensePageState();
}

class _BusinessLicensePageState extends State<BusinessLicensePage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _licenseNumberController = TextEditingController();
  final _addressController = TextEditingController();
  bool _isLongTerm = false;
  DateTime? _endDate;
  DateTime? _startDate;
  late ImagePicker _imagePicker;
  XFile? _licensePhotoFile;

  @override
  void initState() {
    super.initState();
    _imagePicker = ImagePicker();
    _nameController.text = widget.state.company["companyName"] ?? '';
    _licenseNumberController.text = widget.state.company["unifiedSocialCreditCode"] ?? '';
    _addressController.text = widget.state.company["businessLicenseAddress"] ?? '';
    _isLongTerm = widget.state.company["isBusinessLicenseLongTerm"] ?? false;
    _endDate = widget.state.company["businessLicenseEndDate"] != null 
      ? DateTime.parse(widget.state.company["businessLicenseEndDate"]) 
      : null;
    _startDate = widget.state.company["businessLicenseStartDate"] != null 
      ? DateTime.parse(widget.state.company["businessLicenseStartDate"]) 
      : null;
  }

  @override
  void dispose() {
    _nameController.dispose();
    _licenseNumberController.dispose();
    _addressController.dispose();
    super.dispose();
  }

  void _showImageSourceOptions() {
    bool isPickerActive = false;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        title: const Text('选择图片来源'),
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _takePhoto().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("拍照操作错误: $e");
                });
              });
            },
            child: const Text('拍照'),
          ),
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _pickImage().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("选择图片操作错误: $e");
                });
              });
            },
            child: const Text('从相册选择'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  Future<void> _takePhoto() async {
    try {
      var status = await Permission.camera.status;
      if (status.isDenied) {
        await Permission.camera.request();
      } else if (status.isGranted) {
        final picker = ImagePicker();
        final pickedImage = await picker.pickImage(
          source: ImageSource.camera,
          imageQuality: 80,
        );
        
        if (pickedImage != null && mounted) {
          setState(() {
            _licensePhotoFile = pickedImage;
          });
        }
      }
    } catch (e) {
      print("拍照错误: ${e.toString()}");
      EasyLoading.showError("拍照失败：${e.toString()}");
    }
  }

  Future<void> _pickImage() async {
    try {
      final picker = ImagePicker();
      final pickedImage = await picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );
      
      if (pickedImage != null && mounted) {
        setState(() {
          _licensePhotoFile = pickedImage;
        });
      }
    } catch (e) {
      print("选择图片错误: ${e.toString()}");
      EasyLoading.showError("选择图片失败：${e.toString()}");
    }
  }

  Future<String?> _uploadImage() async {
    try {
      EasyLoading.show(status: "上传中...");
      final file = File(_licensePhotoFile!.path);
      
      // 检查文件大小是否超过1M
      final fileSize = await file.length();
      final sizeInMB = fileSize / (1024 * 1024);
      if (sizeInMB > 1) {
        EasyLoading.dismiss();
        EasyLoading.showToast("请上传小于1M的图片");
        return null;
      }

      FormData formData = FormData();
      formData.files.add(MapEntry(
        "file",
        await MultipartFile.fromFile(file.path, filename: "business_license_${DateTime.now().millisecondsSinceEpoch}.jpg")
      ));

      Map res = await commonApi.upload(formData);
      EasyLoading.dismiss();

      if (res["code"].toString() != "200") {
        EasyLoading.showError("上传失败：${res["msg"] ?? "未知错误"}");
        return null;
      }

      return res["data"]["url"];
    } catch (e) {
      EasyLoading.dismiss();
      print("上传图片错误: ${e.toString()}");
      EasyLoading.showError("上传失败：${e.toString()}");
      return null;
    }
  }

  void _selectDate(bool isStart) {
    DateTime selectedDate = isStart ? (_startDate ?? DateTime.now()) : (_endDate ?? DateTime.now());
    
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 300,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () {
                      setState(() {
                        if (isStart) {
                          _startDate = selectedDate;
                        } else {
                          _endDate = selectedDate;
                        }
                      });
                      Navigator.pop(context);
                    },
                    child: const Text('确定'),
                  ),
                ],
              ),
              Expanded(
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: selectedDate,
                  minimumDate: DateTime(1900),
                  maximumDate: DateTime(2100),
                  onDateTimeChanged: (DateTime newDate) {
                    selectedDate = newDate;
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _saveForm() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    // 检查是否上传了营业执照照片
    if ((widget.state.company["businessLicenseImg"]?.isEmpty ?? true) && _licensePhotoFile == null) {
      EasyLoading.showError('请上传营业执照照片');
      return;
    }

    // 检查有效期
    if (!_isLongTerm) {
      if (_startDate == null) {
        EasyLoading.showError('请选择有效期开始时间');
        return;
      }
      if (_endDate == null) {
        EasyLoading.showError('请选择有效期结束时间');
        return;
      }
      if (_startDate!.isAfter(_endDate!)) {
        EasyLoading.showError('开始时间不能晚于结束时间');
        return;
      }
    }

    EasyLoading.show(status: "保存中...");

    try {
      // 上传新图片（如果有）
      String? photoUrl;
      if (_licensePhotoFile != null) {
        photoUrl = await _uploadImage();
      }

      widget.state.updateCompanyBusinessLicenseInfo(
        companyName: _nameController.text,
        unifiedSocialCreditCode: _licenseNumberController.text,
        businessLicenseAddress: _addressController.text,
        isBusinessLicenseLongTerm: _isLongTerm,
        businessLicenseStartDate: _startDate?.toIso8601String(),
        businessLicenseEndDate: _isLongTerm ? null : _endDate?.toIso8601String(),
        businessLicenseImg: photoUrl ?? widget.state.company["businessLicenseImg"],
      );

      widget.onStateChanged();
      EasyLoading.dismiss();
      EasyLoading.showSuccess("保存成功");
      if (mounted) {
        Navigator.pop(context);
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError("保存失败：${e.toString()}");
    }
  }

  // 只读模式提示
  Widget _buildReadOnlyTip() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.blue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '当前信息为只读状态，无法修改',
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageUploadSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              '营业执照照片',
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Text(
              ' *',
              style: TextStyle(
                color: Colors.red,
                fontSize: 16,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: widget.isReadOnly ? null : _showImageSourceOptions,
          child: Container(
            width: double.infinity,
            height: 200,
            decoration: BoxDecoration(
              color: ThemeVars.colorBackground,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: ThemeVars.colorBorder),
            ),
            child: (widget.state.company["businessLicenseImg"]?.isNotEmpty ?? false) || _licensePhotoFile != null
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: (widget.state.company["businessLicenseImg"]?.isNotEmpty ?? false)
                        ? Image.network(
                            widget.state.company["businessLicenseImg"]!,
                            fit: BoxFit.cover,
                          )
                        : Image.file(
                            File(_licensePhotoFile!.path),
                            fit: BoxFit.cover,
                          ),
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.add_photo_alternate_outlined, size: 50),
                      const SizedBox(height: 8),
                      const Text(
                        '点击上传营业执照照片',
                        style: TextStyle(
                          color: ThemeVars.colorTextSec,
                        ),
                      ),
                    ],
                  ),
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          '请上传1M内的彩色照片or彩色扫描件or加盖公章鲜章的复印件，可添加"微信支付"相关水印（如微信支付认证）',
          style: TextStyle(
            color: ThemeVars.colorTextSec,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '营业执照照片',
      child: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            // 只读提示
            if (widget.isReadOnly) _buildReadOnlyTip(),
            _buildImageUploadSection(),
            const SizedBox(height: 24),
            const Text(
              '请核对营业执照信息是否正确',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _nameController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '商户名称',
                hintText: '请输入商户名称',
                suffixIcon: Icon(Icons.business_outlined),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入商户名称';
                }
                if (value.length < 2) {
                  return '商户名称长度不能小于2个字符';
                }
                if (value.length > 100) {
                  return '商户名称长度不能超过100个字符';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _licenseNumberController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '注册号/统一社会信用代码',
                hintText: '请输入注册号/统一社会信用代码',
                suffixIcon: Icon(Icons.numbers_outlined),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入注册号/统一社会信用代码';
                }
                if (!RegExp(r'^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$').hasMatch(value)) {
                  return '请输入正确的统一社会信用代码';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _addressController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '注册地址',
                hintText: '请输入注册地址',
                suffixIcon: Icon(Icons.location_on_outlined),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入注册地址';
                }
                if (value.length < 5) {
                  return '地址长度不能小于5个字符';
                }
                if (value.length > 200) {
                  return '地址长度不能超过200个字符';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Checkbox(
                  value: _isLongTerm,
                  onChanged: widget.isReadOnly ? null : (value) {
                    setState(() {
                      _isLongTerm = value ?? false;
                      if (_isLongTerm) {
                        _endDate = null;
                        _startDate = null;
                      }
                    });
                  },
                ),
                const Text('结束时间是否为长期'),
              ],
            ),
            if (!_isLongTerm) ...[
              const SizedBox(height: 16),
              ListTile(
                title: const Text('有效期开始时间'),
                subtitle: Text(_startDate != null
                    ? DateTools.formatTime(_startDate!.millisecondsSinceEpoch, format: "{y}-{m}-{d}")
                    : '请选择'),
                trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                onTap: widget.isReadOnly ? null : () => _selectDate(true),
              ),
              ListTile(
                title: const Text('有效期结束时间'),
                subtitle: Text(_endDate != null
                    ? DateTools.formatTime(_endDate!.millisecondsSinceEpoch, format: "{y}-{m}-{d}")
                    : '请选择'),
                trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                onTap: widget.isReadOnly ? null : () => _selectDate(false),
              ),
            ],
            const SizedBox(height: 24),
            // 只有在非只读模式下才显示保存按钮
            if (!widget.isReadOnly)
              SizedBox(
                width: double.infinity,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeVars.colorPrimary,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 